package com.dm.cloud.core.mode;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserPermission {
    /**
     * 权限
     */
    private Map<String, List<FunctionPermissions>> funcs = new HashMap<>();

    /**
     * 应用权限列表
     */
    private List<String> apps = new ArrayList<>();

    public boolean hasCode(String code) {
        for (List<FunctionPermissions> value : funcs.values()) {
            if(value.stream().anyMatch(func -> code.equals(func.code))){
                return true;
            }
        }
        return false;
    }

    /**
     * 包含视图
     *
     * @param view
     * @return
     */
    public boolean hasView(String view) {
        for (List<FunctionPermissions> value : funcs.values()) {
            if(value.stream().anyMatch(func -> view.equals(func.view))){
                return true;
            }
        }
        return false;
    }

    /**
     * app权限
     *
     * @param permission
     * @return
     */
    public boolean hasApp(String permission) {
        return apps.contains(permission);
    }

    public void setFuncs(List<FunctionPermissions> setFuncs) {

        for (FunctionPermissions permission : setFuncs) {
            if (!apps.contains(permission.getAppCode())) {
                apps.add(permission.getAppCode());
            }
            String appCode = permission.getAppCode();
            if (funcs.containsKey(appCode)) {
                funcs.get(appCode).add(permission);
            } else {
                List<FunctionPermissions> appFuncs = new ArrayList<>();
                appFuncs.add(permission);
                funcs.put(appCode,appFuncs);
            }
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    public static class FunctionPermissions {
        /**
         * 权限ID
         */
        private String id;

        /**
         * 父级权限ID
         */
        private String pId;

        /**
         * 权限项名称
         */
        private String name;
        /**
         * 权限项编码
         */
        private String code;
        /**
         * 权限项view
         */
        private String view;
        /**
         * 应用id
         */
        private String appCode;

    }

}
